import { LoginForm, User } from '#/api/auth';
import { Response } from '#/api/response';
import { useStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import pinia from "..";
import { login } from '~/api/auth';

const useAuth = defineStore('auth', {
    state() {
        return {
            TOKEN: useStorage<string | null>('auth.token', null),
            USER: useStorage<User>('auth.user', {})
        }
    },
    getters: {
        user: s => s.USER,
        token: s => s.TOKEN,
        isAuth: s => !!s.TOKEN
    },
    actions: {
        setToken(token: string | null = null) {
            this.TOKEN = token;
        },
        setUser(user: User = {}) {
            this.USER = user;
        },
        login() {

            this.setToken('111');
            this.setUser({
                id: 1,
                name: '你好',
                username: 'test',
                avatar:'https://img.zcool.cn/community/01e1805e900b3ea80120a895b31d6f.jpg?x-oss-process=image/resize,m_fill,w_160,h_160,limit_0/auto-orient,1/sharpen,100/quality,q_100/format,webp'
            });
        },
        // login(formData: LoginForm) {
        //     return new Promise<Response>((resolve, reject) => {
        //         login(formData).then(res => {
        //             this.setToken(res.data.token);
        //             this.setUser(res.data.user);
        //             resolve(res.data);
        //         }).catch(reject)
        //     })
        // },
        logout() {
            this.setToken();
            this.setUser();
        }
    }
})

const useAuthWithout = () => useAuth(pinia);

export { useAuth, useAuthWithout };